﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Main
{
    public partial class Users : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ID"] != null)
            {
                if (Session["LIMITEDUSER"] == null)
                {
                    btnNewUser.Visible = true;
                    btnShowUsers.Visible = true;
                    listUsers.Visible = false;
                }
                else if (Session["LIMITEDUSER"] == "true")
                {
                    Response.Redirect("Default.aspx");
                }

            }
            else
                Response.Redirect("Login.aspx");
        }

        /// <summary>
        /// opens a new page for creating a new user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void NewUser_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/CreateNewUser.aspx");
        }

        /// <summary>
        /// triggers listing of all existing users on SQL Azure
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ShowUser_Click(object sender, EventArgs e)
        {
            listUsers.Visible = true;
            listUsers.Items.Clear();
            ControlUsers.Control users = new ControlUsers.Control();
            if (!ListAllUsers(users.ViewUsers(Session["Company"].ToString())))
            {
                listUsers.Items.Add("There are no users defined!");
            }
        }

        /// <summary>
        /// returns list of all existing users on SQL Azure
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private Boolean ListAllUsers(List<User> list)
        {
            foreach (var Result in list)
            {
                if (list.Count == 0)
                {
                    return false;
                }
                else if (Result.name != "admin" && Result.name != "TECHNOSTORE")
                {
                    ListItem userItem = new ListItem();
                    userItem.Text = Result.name + "   " + Result.surname + ", " + Result.email + " - " + Result.phone + "  IsAdmin: " + Result.isadmin;
                    listUsers.Items.Add(userItem);
                }
            }
            return true;
        }
    }
}